package com.intelligent.system.auth.config;

import com.intelligent.system.auth.filter.OAuth2TokenAuthenticationFilter;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private OAuth2TokenAuthenticationFilter oauth2TokenAuthenticationFilter;

    @Resource
    private OAuth2LoginSuccessHandler oauth2LoginSuccessHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
            .authorizeRequests()
                .antMatchers(
                        "/**",
                    "/api/oauth/**",
                    "/error",
                    "/swagger-ui.html",
                    "/swagger-ui/**",
                    "/swagger-resources/**",
                    "/v2/api-docs",
                    "/v3/api-docs",
                    "/webjars/**"
                ).permitAll()
                .anyRequest().authenticated()
                .and()
            .oauth2Login()
                .successHandler(oauth2LoginSuccessHandler)
                .and()
            .addFilterBefore(oauth2TokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
